class AuthController < ApplicationController
  before_filter :spam_required, :only=>['create_save','create']
  #layout false

  def login

  end  

  def do_login
    session[:user] = User.authenticate(params[:user][:email], params[:user][:clearpassword])
    if online
      redirect_to_stored
    else
      flash[:error] = "Kunde inte logga in."
      render :action => :login
    end
  end

  def logout
    session[:user] = nil
    redirect_to "/"
  end

  def counties
    @counties = County.find_all_by_province_id(params[:id], :order => "name")
    render :partial => "counties"
  end

  def create
    load_params_from_session
    #@provinces = Province.find(:all, :order => "name")
    #@counties = County.find_all_by_province_id(params[:id], :order => "name")
    @user = User.new
    @user.county_id = @county.id if @county
    render :layout => false
  end

  def create_save
    load_params_from_session
    params[:user][:county_id] = params[:user][:county_id].to_i
    @user = User.new(params[:user])
    if @user.save
      session[:user] = User.authenticate(@user.email, @user.clearpassword)
      redirect_to_stored
    else
      #@provinces = Province.find(:all, :order => "name")
      #@provinces = Province.find(:all, :order => "name")
      #@province = @user.county.province if @user.county
      #@counties = County.find_all_by_province_id(@province, :order => "name")
      render :action => :create
    end
  end

  def redirect_to_stored
    if @return_to = session[:return_to]
      session[:return_to] = nil
      redirect_to @return_to
    else
      redirect_to :controller=>'index', :action => 'show'
    end
  end
end
